/**
 * 
 */
package it.unical.canonaco.rende.igpe.game.cbv.guilayer.mainmenu;


import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JButton;

/**
 * @author Massimo Canonaco
 */
public class ActionEventMenuSelectionManager implements KeyListener, FocusListener, MouseMotionListener {

	/**It's the key value for selecting the previous component.*/
	private final int PREVIOUS_KEY;
	
	/**It's the key value for selecting the next component.*/
	private final int NEXT_KEY;
	
	/**It's the key value for clicking the actual component.*/
	private final int ACTION_KEY;
	
	/** */
	private KeyboardFocusManager manager;
	
	/** */
	public ActionEventMenuSelectionManager(int previous, int next, int action)
	{
		PREVIOUS_KEY = previous;
		NEXT_KEY = next;
		ACTION_KEY = action;
		manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
	}
	
	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
	 */
	@Override
	public void keyPressed(KeyEvent arg0) 
	{
		final int key = arg0.getKeyCode();
		
		if (key == PREVIOUS_KEY) 
		{
			manager.getFocusOwner().transferFocusBackward();
		} 
		else if (key == NEXT_KEY) 
		{
			manager.getFocusOwner().transferFocus();
			
		}
		else if(key == ACTION_KEY)
		{
			((JButton)manager.getFocusOwner()).doClick();
		}
	}

	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
	 */
	@Override
	public void keyReleased(KeyEvent arg0) 
	{
		// Do nothing.
	}

	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
	 */
	@Override
	public void keyTyped(KeyEvent arg0) 
	{
		// Do nothing.
	}

	@Override
	public void focusGained(FocusEvent arg0) 
	{
		((JButton)arg0.getSource()).setSelected(true);
	}

	@Override
	public void focusLost(FocusEvent arg0) 
	{
		((JButton)arg0.getSource()).setSelected(false);
	}

	@Override
	public void mouseDragged(MouseEvent e) 
	{
		//TODO: draw CLIC image
	}

	@Override
	public void mouseMoved(MouseEvent e) 
	{
			if(manager.getFocusOwner() instanceof JButton)
			{
				((JButton)manager.getFocusOwner()).setSelected(false);
			}
			((JButton)e.getSource()).setSelected(true);
			((JButton)e.getSource()).requestFocusInWindow();
		
	}

}
